package org.pzy.opensource.webview;

import com.sun.javafx.scene.web.Debugger;
import com.sun.javafx.webkit.WebConsoleListener;
import com.vladsch.javafx.webview.debugger.DevToolsDebuggerServer;
import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import netscape.javascript.JSObject;

import java.io.File;
import java.lang.reflect.Field;

public class FxApp extends Application {

    //必须公有
    public static class A {

        public String showInfo(String info) {
            return "A{info=" + info + "}";
        }
    }


    A apps = new A();

    WebEngine webEngine;


    @Override
    public void start(Stage stage) throws Exception {
        final WebView browser = new WebView();
        webEngine = browser.getEngine();
        String url = new File("filePage.html").toURI().toURL().toString();
        System.out.println(url);
        WebConsoleListener.setDefaultListener(new WebConsoleListener() {
            @Override
            public void messageAdded(WebView webView, String message, int lineNumber, String sourceId) {
                System.out.println("Console: " + message + " [" + sourceId + ":" + lineNumber + "] ");
            }
        });

        webEngine.load(url);
        webEngine.getLoadWorker().stateProperty().addListener(
                (ObservableValue<? extends Worker.State> ov, Worker.State oldState,
                 Worker.State newState) -> {

                    if (newState == Worker.State.SUCCEEDED) {
                        JSObject win = (JSObject) webEngine.executeScript("window");
                        win.setMember("apps", apps);//设置变量
                    }
                });

        Button button1 = new Button("java调JS方法");
        button1.setOnAction(event -> {
            try {

                JSObject win = (JSObject) webEngine.executeScript("window");
                //webEngine.executeScript("show()");//执行js函数
                //win.call("show","a","b");
                win.eval("show('a','b')");
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        VBox stackPane = new VBox();
        stackPane.setSpacing(20);
        stackPane.getChildren().addAll(button1, browser);
        Scene scene = new Scene(stackPane, 600, 400);

        scene.setRoot(stackPane);
        stage.setScene(scene);
        stage.show();

    }

    public static void main(String[] args) {
        launch(args);
    }

}
